﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace LowLevelGraphics.Filter
{
    public delegate bool ColorProcessing(UnsafeBitmap bitmap, int x, int y, Color color);

    /// <summary>
    /// 
    /// </summary>
    public class ColorSuppression : BaseForeBackgroundColorFilter
    {
        ColorProcessing m_Delegate = null;

        /// <summary>
        /// Initializes a new instance of the <see cref="ColorSuppression"/> class.
        /// </summary>
        public ColorSuppression()
            : this(new ColorProcessing(Suppression))
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ColorSuppression"/> class.
        /// </summary>
        /// <param name="_delegate">The _delegate.</param>
        public ColorSuppression(ColorProcessing _delegate)
        {
            m_Delegate = _delegate;
            
        }

        /// <summary>
        /// Execute this Filter
        /// A Debug Statement is written if a concrete Filter is called
        /// </summary>
        /// <param name="_bitmap"></param>
        /// <returns></returns>
        public override UnsafeBitmap Execute(UnsafeBitmap _bitmap)
        {
            UnsafeBitmap bitmap = _bitmap;

            int nWidth = bitmap.Width;
            int nHeight = bitmap.Height;

            int y = 0;
            int x = 0;

            Color color = Color.Transparent;
            bool bSuppression = false;

            for (y = 0; y < nHeight; y++)
            {
                for (x = 0; x < nWidth; x++)
                {
                    color = bitmap.GetPixel(x, y);
                    bSuppression = m_Delegate(bitmap, x, y, color);
                    if (bSuppression)
                    {
                        bitmap.SetPixel(x, y, m_ColorBackground);
                    }
                }
            }
            return _bitmap;
        }

        /// <summary>
        /// Suppresses all colors which got a brightness below 0.45f
        /// </summary>
        /// <param name="bitmap"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="color"></param>
        /// <returns></returns>
        private static bool Suppression(UnsafeBitmap bitmap, int x, int y, Color color)
        {
            return color.GetBrightness() < 0.45f;
        }

        /// <summary>
        /// This is used to clone a filter, each filter must implement it's own clone functionality
        /// </summary>
        /// <returns></returns>
        public override object Clone()
        {
            return new ColorSuppression(this.m_Delegate);
        }
    }
}
